<?php
namespace common\component;


class CacheHelper
{
    /**
     * 缓存时间
     * @var int
     */
    private $expire = 3600;
    /**
     * 缓存key
     * @var string
     */
    private $key;

    /**
     * 缓存器
     * @var
     */
    private $cache;

    private function __construct($clazz, $prefix,$expire = 0)
    {
        if ($pos = strripos($clazz, "\\")) {
            $clazz = substr($clazz, $pos + 1);
        }
        $className = strtolower($clazz);
        if (!$clazz || !isset(\Yii::$app->params['cacheKeys'][$className])) {
            $className = "default";
        }
        $this->cache = \Yii::$app->params['cacheKeys']['cacheid'];
        //组合唯一key
        $this->key = \Yii::$app->params['cacheKeys'][$className]["prefix"];
        if (is_array($prefix)) {
            $this->key .= ":" . implode(":", $prefix);
        } else {
            $this->key .= ":" . $prefix;
        }
        $this->expire = $expire > 0 ? $expire :\Yii::$app->params['cacheKeys'][$className]['expire'];
    }


    public static function getInstance($clazz, $key,$expire = 0)
    {
        return new self($clazz,$key,$expire);
    }

    /**
     * 获取缓存
     * @return mixed
     */
    public function getCache()
    {
        $isCache = \Yii::$app->params["enableCache"];
        if ($isCache) {
            $cacheId = $this->cache;
            $data = \Yii::$app->$cacheId->get($this->key);
            return $data;
        }
       return false;
    }

    /**
     * 设置缓存
     * @param $data
     * @return mixed
     */
    public function setCache($data)
    {
        $isCache = \Yii::$app->params["enableCache"];
        if ($isCache) {
            $cacheId = $this->cache;
            return \Yii::$app->$cacheId->set($this->key, $data, $this->expire);
        }
        return true;
    }

    /**
     * 删除缓存
     * @return mixed
     */
    public function deleteCache()
    {
        $cacheId = $this->cache;
        return \Yii::$app->$cacheId->delete($this->key);
    }
}
